﻿var publicModule = angular.module('publicModule', []);


publicModule.controller('TitleController', ['$scope', '$http', function ($scope, $http) {
    $scope.titleId;
    $scope.title = [];
    $scope.reservationsForTitle = [];
    $scope.userHasAvailableReservation = false;
    $scope.userId = 0;
    $scope.user = [];
    $scope.usersLoansForThisTitle = [];

    $scope.init = function (titleId, userId) {
        
        $http.defaults.headers.common.Authorization = getAuthorizationHeader(userId, '');

        console.log("init with titleId: " + titleId + " and userId: "+userId);
        $scope.titleId = titleId;
        $scope.userId = userId;

        //load title information
        $http.get('/api/title/' + titleId).success(function (data) {
            console.log("loaded titleinformation...");
            $scope.title = data;
            console.log(data);
        });

        //load reservations for title
        $http.get('/api/reservationsForTitle/' + titleId).success(function (data) {
            console.log("loaded reservations for title...");
            $scope.reservationsForTitle = data;
            console.log(data);
        });

        if (userId > 0) {
            //load userinformation
            $http.get('/api/user/').success(function (data) {
                console.log("loaded userinformation...");
                console.log(data);
                $scope.user = data;
            }).error(function (data) {
                console.error("could not load userinformation for user with id " + userId);
            });


            //load information if user has an availableReservation
            $http.get('/api/reservation/?availableReservation&titleId=' + titleId).success(function (data) {
                if (data != null) {
                    $scope.userHasAvailableReservation = true;
                } else {
                    $scope.userHasAvailableReservation = false;
                }

                console.log("userHasAvailableReservation: " + data);
            });

            //load users loans for this title:
            $http.get('/api/loan/').success(function (data) {
                console.log("loaded users actives loans for this title...");
                $.each(data, function (key, val) {
                    if (val.Loanable.Title.TitleId == $scope.titleId) {
                        $scope.usersLoansForThisTitle.push(val);
                    }
                });

                console.log($scope.usersLoansForThisTitle);
            });


        }

        
    }

    $scope.userIsOwnerOfAtLeastOneLoanable = function () {
        console.log("check if user is owner of at least one loanable");
        userIsOwner = false;

        $.each($scope.title.Loanables, function (key, val) {
            if (val.Owner.UserId == $scope.userId) {
                console.log("user is owner of loanable " + val.LoanableId);
                userIsOwner = true;
            }
        });

        return userIsOwner;
    }

    $scope.userHasBorrowedLoanable = function (loanableId) {
        console.log("check if user has currently borrowed the loanable with id " + loanableId);
        userBorrowedThisLoanable = false;
        $.each($scope.usersLoansForThisTitle, function (key, val) {
            if (val.Loanable.LoanableId == loanableId) {
                console.log("user has currently borrowed this loanable...");
                userBorrowedThisLoanable = true;
            }
        });

        return userBorrowedThisLoanable;
    }

    $scope.getNumberOfLoanables = function () {
        return $scope.title.Loanables.length;
    }

    $scope.getNumberOfCurrentLoans = function () {
        count = 0;

        $.each($scope.title.Loanables, function (key, val) {
            if (val.Status == 1) {
                //borrowed
                count++;
            }
        });

        return count;
    }

    $scope.getStatusForLoanable = function (loanableId) {
        console.log("get status for loanable with id: " + loanableId);
        //get the loanable
        var loanable = [];
        $.each($scope.title.Loanables, function (key, val) {
            if (val.LoanableId == loanableId) {
                loanable = val;
            }
        });
        console.log(loanable);
        console.log("simple status: " + loanable.Status);

        if (loanable.Status == 0) {
            return LOANABLE_STATUS_ENUM.AVAILABLE;
            //return "Available";
        } else if(loanable.Status == 1) {
            return LOANABLE_STATUS_ENUM.BORROWED;
            //return "Borrowed";
        } else if(loanable.Status == 2) {
            //the loanable is reserved...

            console.log("reservations for this title: ");
            console.log($scope.reservationsForTitle);

            if ($scope.userId > 0) {
                if ($scope.userHasAvailableReservation) {
                    //user has a reservation
                    return LOANABLE_STATUS_ENUM.AVAILABLE_RESERVED_FOR_USER;
                    //return "Available (reserved for you)";
                } else {
                    //user has no reservation
                    return LOANABLE_STATUS_ENUM.AVAILABLE_RESERVED_FOR_OTHER_USER;
                    //return "Available but reserved";
                }
            } else {
                //more reservations as available loanables and user is not logged in
                return LOANABLE_STATUS_ENUM.AVAILABLE_RESERVED_FOR_OTHER_USER;
                //return "Available but reserved";
            }
        } else if (loanable.Status == 3) {
            return LOANABLE_STATUS_ENUM.UNAVAILABLE_FROM_OWNER;
        } else if (loanable.Status == 4) {
            return LOANABLE_STATUS_ENUM.RECALLED;
        }
    }

    $scope.currentUserIsOwnerOfLoanable = function (loanableId) {
        isOwner = false;

        $.each($scope.title.Loanables, function (key, val) {
            if (val.LoanableId == loanableId && val.Owner.UserId == $scope.userId) {
                isOwner = true;
            }
        });
        return isOwner;
    }

    $scope.userHasTitleReserved = function () {
        console.log("check if user has a reservation for this title..");
        userReservedTitle = false;

        console.log($scope.reservationsForTitle);
        $.each($scope.reservationsForTitle, function (key, val) {
            console.log(val);
            if (val.User.UserId == $scope.userId) {
                userReservedTitle = true;
            }
        });

        console.log("user has reserved: " + userReservedTitle);
        return userReservedTitle;
    }

    $scope.reserveTitle = function () {
        console.log("reserving title...");

        $http.defaults.headers.common.Authorization = getAuthorizationHeader($scope.userId, '');
        console.log("authheader: " + $http.defaults.headers.common.Authorization);
        $http({
            method: 'POST',
            url: '/api/reservation?titleId=' + $scope.titleId,
        }).success(function (data, status, headers, config) {
              console.log("reservation success");
              setHttpMessageDynamic("Reservation has been added", true);
              $('#reserveButton').hide();
          }).
          error(function (data, status, headers, config) {
              console.log("reservation failed");
              console.log("data: ", data);
              console.log("status: ", status);
              console.log("header: ",headers);
              setHttpMessageDynamic("Reservation could not be added. Did you already add a reservation for this title or have you currently borrowed a loanable?", false);
          });
    }

    $scope.makeLoanableUnavailable = function (loanableId, successCallback, errorCallback) {
        console.log("make loanable unavailable " + loanableId);

        //get loanable
        var loanable = null;
        $.each($scope.title.Loanables, function (key, val) {
            if (val.LoanableId == loanableId) {
                loanable = val;
            }
        });
        console.log("loanable: ", loanable);

        if (loanable != null && loanable.Owner.UserId == $scope.userId) {

            if (!loanable.UnavailableFromOwner) {

                $http.defaults.headers.common.Authorization = getAuthorizationHeader($scope.userId, '');
                $http({
                    method: 'PUT',
                    url: '/api/loanable/' + loanableId + '/recall',
                }).success(function (data, status, headers, config) {
                    console.log("mark unavailable success");
                    successCallback();
                }).error(function (data, status, headers, config) {
                    console.error("mark unavailable failed");
                    console.log("data: ", data);
                    console.log("status: ", status);
                    console.log("header: ", headers);
                    errorCallback();
                });

            } else {
                setHttpMessageDynamic("This loanable is already marked as unavailable / recalled", false);
            }

        } else {
            setHttpMessageDynamic("Only the owner of a loanable can mark is as unavailable/recall it", false);
        }
    }

    $scope.markAsUnavailable = function (loanableId) {
        console.log("mark loanable as unavailable");

        $scope.makeLoanableUnavailable(loanableId, function () {
            //success
            setHttpMessage("loanable was marked as unavailable", true);
            location.reload();
        }, function () {
            //fail
            setHttpMessageDynamic("loanable could not be marked as unavailable");
        });
    }

    $scope.removeLoanable = function (loanable) {
    	if (confirm("This action removes the loanable from Doelibs. Would you like to proceed?") == true) {
    		console.log("Remove loanable from Doelibs");

    		$http.defaults.headers.common.Authorization = getAuthorizationHeader($scope.userId, '');
    		$http({
    			method: 'DELETE',
    			url: "/api/loanable/" + loanable,
    		}).success(function (data, status, headers, config) {
    			setHttpMessage("Loanable was removed successfully", true);
    			location.reload();
    		}).error(function (data, status, headers, config) {
    			console.error(data)
    			console.error(status)
    			console.error(headers)
    			setHttpMessageDynamic("Loanable could not be removed");
    		});
    	}
    }

    $scope.recallLoanable = function (loanableId) {
        console.log("recall loanable");

        $scope.makeLoanableUnavailable(loanableId, function () {
            //success
            setHttpMessage("loanable was recalled", true);
            location.reload();
        }, function () {
            //fail
            setHttpMessageDynamic("loanable could not be recalled");
        });
    }

    $scope.markAsAvailable = function (loanableId) {
        console.log("mark loanable (" + loanableId + ") as available");

        //get loanable
        var loanable = null;
        $.each($scope.title.Loanables, function (key, val) {
            if (val.LoanableId == loanableId) {
                loanable = val;
            }
        });
        console.log("loanable: ", loanable);

        if (loanable != null && loanable.Owner.UserId == $scope.userId) {

            if (loanable.UnavailableFromOwner) {

                $http.defaults.headers.common.Authorization = getAuthorizationHeader($scope.userId, '');
                $http({
                    method: 'PUT',
                    url: '/api/loanable/' + loanableId + '/markAsAvailable',
                }).success(function (data, status, headers, config) {
                    console.log("mark available success");
                    
                    setHttpMessage("loanable was marked as available again", true);
                    location.reload();
                }).error(function (data, status, headers, config) {
                    console.error("mark available failed");
                    console.log("data: ", data);
                    console.log("status: ", status);
                    console.log("header: ", headers);
                    
                    setHttpMessageDynamic("loanable could not be marked as available again", false);
                });

            } else {
                setHttpMessageDynamic("This loanable is already marked as available", false);
            }

        } else {
            setHttpMessageDynamic("Only the owner of the loanable can mark is as available again", false);
        }

    }

    $scope.checkOutLoanable = function (loanableId) {
        console.log("checkOut loanable with id " + loanableId);

        $http.defaults.headers.common.Authorization = getAuthorizationHeader($scope.userId, '');
        $http({
            method: 'POST',
            url: '/api/loanable/' + loanableId
        }).success(function (data, status, headers, config) {
            console.log("loan added");
            setHttpMessage("Loanable checked out", true);
            location.reload();
        }).error(function (data, status, headers, config) {
              console.log("checkout failed");
              console.log("data: ", data);
              console.log("status: ", status);
              console.log("header: ", headers);
              setHttpMessageDynamic("Loanable could not be checked out", false);
          });
    }

    $scope.checkInLoanable = function (loanableId) {
        console.log("checkIn loanable with id " + loanableId);

        var loan = [];
        loanFound = false;
        $.each($scope.usersLoansForThisTitle, function (key, val) {
            if (val.Loanable.LoanableId == loanableId) {
                loan = val;
                loanFound = true;
            }
        });
        console.log(loan);

        if (loanFound) {

            $http.defaults.headers.common.Authorization = getAuthorizationHeader($scope.userId, '');
            $http({
                method: 'DELETE',
                url: '/api/loan/' + loan.LoanId
            }).success(function (data, status, headers, config) {
                console.log("loan checked in");
                setHttpMessage("Loanable checked in", true);
                location.reload()
            }).error(function (data, status, headers, config) {
                console.log("checkout failed");
                console.log("data: ", data);
                console.log("status: ", status);
                console.log("header: ", headers);
                setHttpMessageDynamic("Loanable could not be checked in", false);
            });
        } else {
            setHttpMessageDynamic("Loanable could not be checked in because you don't have a loan with it", false);
        }
    }
}]);

LOANABLE_STATUS_ENUM = {
    AVAILABLE_RESERVED_FOR_USER: 0,
    AVAILABLE_RESERVED_FOR_OTHER_USER: 1,
    AVAILABLE: 2,
    BORROWED: 3,
    UNAVAILABLE_FROM_OWNER: 4,
    RECALLED: 5
}

/*
LOANABLE_STATUS_ENUM = {
    AVAILABLE_RESERVED_FOR_USER: "Available (reserved for you)",
    AVAILABLE_RESERVED_FOR_OTHER_USER: "Available but reserved",
    AVAILABLE: "Available",
    BORROWED: "Borrowed"
}
*/












publicModule.controller('AuthorController', ['$scope', '$http', function ($scope, $http) {
    
    $scope.authorId = 0;
    $scope.author = [];
    $scope.authorFound = false;

    $scope.init = function (authorId, tableForTitles) {
        console.log("init authorcontroller for authorId " + authorId);
        $scope.authorId = authorId;

        console.log("load author information");
        $http.get('/api/author/' + authorId).success(function (data) {
            console.log(data);
            
            if (data != "null") {
                $scope.author = data;
                $scope.authorFound = true;

                $scope.fillTitleTable(tableForTitles);

            } else {
                console.log("no data available for author with authorId " + authorId);
                $scope.authorFound = false;
            }

            if (!$scope.authorFound) {
                setHttpMessageDynamic("No information for this author found", false);
            }
        });
    }



    $scope.fillTitleTable = function (tableForTitles) {
        console.log("fill datatable with titles from author");

        //set the BookTitle as link:
        var tableData = $scope.author.Titles;
        for (i = 0; i < tableData.length; i++) {
            tableData[i].BookTitle = "<a href='/Title/Get/"+tableData[i].TitleId+"'>" + tableData[i].BookTitle + "</a>";
        }

        $('#' + tableForTitles).DataTable({
            "bFilter": false,
            "data": tableData,
            "columns": [
                { "data": "BookTitle", "title": "Title"},
                { "data": "EditionNumber", "title": "Edition"},
                { "data": "EditionYear", "title": "Year"},
                { "data": "Publisher.Name", "title": "Publisher"}
            ]
        });

        $('#' + tableForTitles).removeClass("dataTable");
    }

}]);

publicModule.controller('TopicController', ['$scope', '$http', function ($scope, $http) {

	$scope.topicId = 0;
	$scope.topic = [];
	$scope.topicFound = false;

	$scope.init = function (topicId, tableForTitles) {
		console.log("init topiccontroller for topicId " + topicId);
		$scope.topicId = topicId;

		console.log("load topic information");
		$http.get('/api/topic/' + topicId).success(function (data) {
			console.log(data);

			if (data != "null") {
				$scope.topic = data;
				$scope.topicFound = true;

				$scope.fillTitleTable(tableForTitles);

			} else {
				console.log("no data available for topic with topicId " + topicId);
				$scope.topicFound = false;
			}

			if (!$scope.topicFound) {
				setHttpMessageDynamic("No information for this topic found", false);
			}
		});
	}

	$scope.fillTitleTable = function (tableForTitles) {
		console.log("fill datatable with titles from topic");

		//set the BookTitle as link:
		var tableData = $scope.topic.Titles;
		for (i = 0; i < tableData.length; i++) {
			tableData[i].BookTitle = "<a href='/Title/Get/" + tableData[i].TitleId + "'>" + tableData[i].BookTitle + "</a>";
		}

		$('#' + tableForTitles).DataTable({
			"bFilter": false,
			"data": tableData,
			"columns": [
                { "data": "BookTitle", "title": "Title" },
                { "data": "EditionNumber", "title": "Edition" },
                { "data": "EditionYear", "title": "Year" },
                { "data": "Publisher.Name", "title": "Publisher" }
			]
		});

		$('#' + tableForTitles).removeClass("dataTable");
	}

}]);

publicModule.controller('LocationCategoryController', ['$scope', '$http', function ($scope, $http) {

    $scope.categoryId = 0;
    $scope.category = [];

    $scope.init = function (catId, tableForTitles) {
        $scope.categoryId = catId;

        $http.get('/api/LoanableLocationCategory/' + catId).success(function (data) {
            console.log("got data", data);
            $scope.category = data;

            $scope.fillTitleTable(tableForTitles);
        }).error(function (data) {
            console.log("error on getting location category details", data)
        });
    }

    $scope.fillTitleTable = function (tableForTitles) {
        //set the BookTitle as link:
        var tableData = [];
        $.each($scope.category.Loanables, function (key, val) {
            var entry = [];
            entry.BookTitle = "<a href='/Title/Get/" + val.TitleId + "'>" + val.Title + "</a>";
            entry.DoeLibSId = val.DoelibsId;
            entry.Status = getStatusAsString(val.LoanableStatus);

            tableData.push(entry);
        });

        $('#' + tableForTitles).DataTable({
            "bFilter": false,
            "data": tableData,
            "columns": [
                { "data": "BookTitle", "title": "Title" },
                { "data": "DoeLibSId", "title": "DoeLibS Identifier" },
                { "data": "Status", "title": "Status" }
            ]
        });

        $('#' + tableForTitles).removeClass("dataTable");
    }

}]);